package com.aliang.shopping.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;

/**
 * 验证码工具类
 */
public class CodeUtil {

    public static LineCaptcha getRandomNUmber() {
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40, 4, 20);
        lineCaptcha.setGenerator(randomGenerator);
        // 重新生成code
        lineCaptcha.createCode();
        return lineCaptcha;
    }

    public static LineCaptcha getMathCode() {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(120, 40, 4, 20);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator(1));
        // 重新生成code
        captcha.createCode();
        return captcha;
    }


    /**
     * 获取运算结果
     *
     * @param code
     * @return
     */
    public static String getMachResult(String code) {
        Integer one = Integer.valueOf(code.substring(0, 1));
        char math = code.charAt(1);
        Integer two = Integer.valueOf(code.substring(2, 3));
        switch (math) {
            case '+':
                return String.valueOf(one + two);
            case '-':
                return String.valueOf(one - two);
            case '*':
                return String.valueOf(one * two);
            case '/':
                return String.valueOf(one / two);
            default:
                return "0";
        }
    }
}
